package com.example.timeplanning_teacher;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class AddRuleActivity extends AppCompatActivity {

    private EditText RuleNameInput;
    private EditText RuleCycleInput;
    private String RuleCycle;
    private Button RuleConfirm;
    private String RuleName;
    private Toast Success;
    private Toast Failure;
    private Toast timeOut_Toast;
    private SharedPreferences sp;
    private String username;
    private String StudentUsername;
    private Integer TimeCycle;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_rule);
        RuleConfirm = findViewById(R.id.RuleConfirm);
        RuleNameInput = findViewById(R.id.RuleName);
        RuleCycleInput = findViewById(R.id.RuleCycle);
        RuleNameInput.setFocusable(true);
        RuleNameInput.setFocusableInTouchMode(true);
        RuleCycleInput.setFocusable(true);
        RuleCycleInput.setFocusableInTouchMode(true);

        Success  = Toast.makeText(AddRuleActivity.this,"成功",Toast.LENGTH_SHORT);
        Failure = Toast.makeText(AddRuleActivity.this,"失败",Toast.LENGTH_SHORT);
        timeOut_Toast = Toast.makeText(AddRuleActivity.this, "网络连接超时", Toast.LENGTH_SHORT);
        sp = getSharedPreferences("parent", Context.MODE_PRIVATE);
        username = sp.getString("username","");
        StudentUsername = sp.getString("student_username","");
        RuleNameInput.requestFocus();

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
//                        Intent intent=new Intent(AddRuleActivity.this, FragmentActivity.class);
//                        startActivity(intent);


                                AddRuleActivity.this.finish();
                        overridePendingTransition(R.anim.no_anim, R.anim.trans_out);
                }
            };
        };
        
        RuleConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RuleName = RuleNameInput.getText().toString().trim();
                RuleCycle = RuleCycleInput.getText().toString().trim();
                TimeCycle = Integer.parseInt(RuleCycle);
                if (RuleName.length() != 0) {
                    if(RuleCycle.length() == 0){
                        Toast.makeText(AddRuleActivity.this,"请输入重复周期",Toast.LENGTH_SHORT).show();
                    }
                    else{
                        if(TimeCycle>365){
                            Toast.makeText(AddRuleActivity.this,"重复周期不要大于365天！",Toast.LENGTH_SHORT).show();
                        }
                        else {
                            MakeRuleThread makeRuleThread = new MakeRuleThread();
                            makeRuleThread.start();
                        }

                    }
                    //选择日期
                } else {
                    Toast.makeText(AddRuleActivity.this, "请先输入名称", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public class MakeRuleThread extends Thread{
        public void run(){
            try {
                String json = "{\n" +
                        "  \"stu_username\": \"" + StudentUsername + "\",\n" +
                        "  \"par_username\": \"" + username + "\",\n" +
                        "  \"rule_name\": \"" + RuleName + "\",\n" +
                        "  \"cycle\": " + TimeCycle + "\n" +
                        "}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://58.58.36.198:9900/rule/makeRule")
                        .post(RequestBody.create(MediaType.parse("application/json"),json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject=new JSONObject(responseData);
                int code=(int)jsonObject.get("code");
                if(code == 100){
                    //Success.show();
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
                else{
                    Failure.show();
                }
            }catch (Exception e){
                e.printStackTrace();
                timeOut_Toast.show();
            }
        }
    }

    //左上角返回键，其他页面相同
    public void backviewonClick(View view) {
        AddRuleActivity.this.finish();
        overridePendingTransition(R.anim.no_anim, R.anim.trans_out);
    }

    //重写手机返回键，添加切换动画，其他页面相同
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AddRuleActivity.this.finish();
            overridePendingTransition(R.anim.no_anim, R.anim.trans_out);
        }
        return super.onKeyUp(keyCode, event);
    }
}